package com.pacs.service;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
//import com.ayez.model.Account;
//import com.ayez.model.FirstClinicals;
//import com.ayez.model.Users;
import com.pacs.tools.LogUtil;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.api.CustomServiceApi.Articles;
import com.pacs.util.SecretUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class WeixinService {
	static {
//		PropKit.use("config.txt");
//		ServiceFactory.init();
//		DruidPlugin plugin = new DruidPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password").trim());
//		ActiveRecordPlugin arp = new ActiveRecordPlugin(plugin); 		
//		_MappingKit.mapping(arp);
//		plugin.start();
//		arp.start();

	}
	private static final PoolingHttpClientConnectionManager POOL_CM = new PoolingHttpClientConnectionManager();

	private static final String CAHR_CODE = "UTF-8";

	// 获取访问TOKEN
	private static final String GET_OAUHT_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

	// 下载图片资源
	private static final String DOWNLOAD_IMAGE = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";

	// 拉取用户信息
	private static final String GET_USERINFO = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
		
	private static final Pattern RESOURCE_PATTERN = Pattern.compile("attachment; filename=\"(.*?)\"");
	
	//业务逻辑请求
	private static final String BASE_URL = PropKit.get("wx_base_url");


	/*
	 * 获取openid
	 */
	public String getOpenId(String code) {
		String url = String.format(GET_OAUHT_TOKEN, PropKit.get("appId"), PropKit.get("appSecret"), code);
		String content = this.doGet(url);
		JSONObject obj = JSON.parseObject(content);
		if (obj.containsKey("errcode")) {
			return null;
		} else {
			return obj.getString("openid");
		}
	}

	/*
	 * 获取用户信息
	 */
	public void getUserInfo(String openid) {
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		String url = String.format(GET_USERINFO, AccessTokenApi.getAccessTokenStr(), openid);
		String content = doGet(url);
		JSONObject obj = JSON.parseObject(content);
		if (obj.containsKey("errcode")) {
		} else {
			System.out.println(obj);
//			Account account = Account.dao.findById(openid);
//			account.setWxIcon(obj.getString("headimgurl"));
//			account.setWxName(obj.getString("nickname"));
//			account.update();
//			if (!account.getUid().isEmpty()) {
//				Users users = Users .dao.findById(account.getUid());
//				users.setIcon(obj.getString("headimgurl"));
//				users.update();
//			}
		}
	}
	
	private String doGet(String url) {
		StringBuilder apiLog = new StringBuilder();
		apiLog.append(url).append("\t").append("params:").append("");
		CloseableHttpClient client = HttpClients.custom().setConnectionManager(POOL_CM).build();
		String content = null; // 返回内容
		try {
			HttpGet get = new HttpGet(url);

			CloseableHttpResponse response = null;
			try {
				response = client.execute(get);
				int code = response.getStatusLine().getStatusCode();
				if (code == 200) {
					content = IOUtils.toString(response.getEntity().getContent(), CAHR_CODE);
				} else {
					content = "{\"40013\":" + code + "}";
				}
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (Exception e) {
			LogUtil.netEaseError(e.getMessage(), e);
			content = "{\"40013\":1000}";
		}
		// 记录日志
		apiLog.append("\t").append("result:").append(content);
		LogUtil.netEaseDebug(apiLog.toString());

		return content;
	}

	/*
	 * 发送模板消息
	 */
	public void sendTemplateMsg(String openid,String url,String event,String userName) {
		if (PropKit.getBoolean("devMode") == true) {
			ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
			String time = sdf.format(new Date());
			String json = TemplateData.New().setTouser(openid)
					.setTemplate_id("eNs4B9rKo_0N-sF1NRmW6PESmTLm8zi_5Vl6ujeFngA").setTopcolor("#743A3A")
					.setUrl(url)
					.add("keyword1", time  , "#743A3A")
					.add("keyword2", event , "#743A3A")
					.add("keyword3", "用药了吗？用药后感觉怎么样？快来说说吧，我们不会将您的资料泄露，完成赢积分！", "#743A3A")
					.build();
			System.out.println(json);
			ApiResult result = TemplateMsgApi.send(json);
			System.out.println(result.getJson());
		}else{
			ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
			String time = sdf.format(new Date());
			String json = TemplateData.New().setTouser(openid)
					.setTemplate_id("U4cjem6T4heIpO6gS92XE2au9ZTr0mJcgutgEoDIpRI").setTopcolor("#743A3A")
					.setUrl(url)
					.add("first"   , event      , "#0DB0EB")
					.add("keyword1", userName         , "")
					.add("keyword2", ""         , "")
					.add("keyword3", time       , "")
					.add("remark"  , "请按时记录哦", "#BBBBBB")
					.build();
			System.out.println(json);
			ApiResult result = TemplateMsgApi.send(json);
			System.out.println(result.getJson());
		}
	}

	public static ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}

	/**
	 * 下载资源 
	 * @param mid
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public Map<String, Object> downloadResource(String mediaId, String token) throws ClientProtocolException, IOException{
		String url = String.format(DOWNLOAD_IMAGE, token, mediaId);
		CloseableHttpClient client 	= HttpClients.custom().setConnectionManager(POOL_CM).build();
			HttpGet get = new HttpGet(url);
			CloseableHttpResponse response 	= null;
			try{
				response 		= client.execute(get);
				int code 		= response.getStatusLine().getStatusCode();
				String fileName = "";
				if (code == 200){
					//获取文件名称
					Header dispositionHeader = response.getFirstHeader("Content-disposition");
					if (dispositionHeader != null){
						String disposition = dispositionHeader.getValue();
						Matcher m = RESOURCE_PATTERN.matcher(disposition);
						if (m.find()){
							fileName = m.group(1);
						}
					}else{
						fileName = UUID.randomUUID().toString();
					}
					Header contentLengthHeader = response.getFirstHeader("Content-Length");
					int len = Integer.parseInt(contentLengthHeader.getValue());
					
					// 存储到本地
					String filePath = "/tmp/" + fileName;
					byte[] buff = new byte[len];
					FileOutputStream output = new FileOutputStream(filePath);
					DataInputStream input = new DataInputStream(response.getEntity().getContent());
					input.readFully(buff);
					output.write(buff);
					input.close();
					output.close();
					Map<String, Object> infos = new HashMap<>();
					infos.put("filePath", filePath);
					infos.put("fileName", fileName);
					infos.put("md5", SecretUtil.md5(buff));
					infos.put("size", len);
					infos.put("data", buff);
					return infos;
				}else{
					return null;
				}
			}finally{
				if (response != null){
					response.close();
				}
			}
	}
	
	/**
	 * 上传图片
	 * @param parents
	 * @param sid
	 * @return
	 */
//	public Boolean uploadMedicineImg(String uid,String mediaId){
//		String imageUrl = uploadWxImgToQiniu(mediaId);
//		FirstClinicals firstClinical = FirstClinicals.dao.findById(uid);
//		if (firstClinical != null) {
//			firstClinical.setRecipeImage(imageUrl);
//			return firstClinical.update();
//		} else {
//			FirstClinicals firstClinicalNew = new FirstClinicals();
//			firstClinicalNew.setUid(uid);
//			firstClinicalNew.setRecipeImage(imageUrl);
//			firstClinicalNew.setCtime(Integer.valueOf(create_timestamp()));
//			return firstClinicalNew.save();
//		}
//	}
	
//	public String uploadWxImgToQiniu(String mediaId) {
//		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
//		try {
//			Map<String, Object> infos = downloadResource(mediaId, AccessTokenApi.getAccessTokenStr());
//			if (infos == null) {
//				return null;
//			}
//			String filePath = (String) infos.get("filePath");
//			String fileName = (String) infos.get("fileName");
//			QiniuService qnService = ServiceFactory.getService(QiniuService.class);
//			String imageUrl = qnService.getQiniuIconUrl(filePath,fileName);
//			return imageUrl;
//		} catch (Exception e) {
//			LogUtil.sysError(e.getMessage(), e);
//			return null;
//		}
//	}
	
	private String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private String create_nonce_str() {
		return UUID.randomUUID().toString();
	}
	
	/*
	 * 发送客服消息
	 */
	public void sendCustomerServiceMessage (String openid, String title, String imgUrl, String remarkText, String url) {
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
		List<Articles> list = new ArrayList<Articles>();
		Articles articles1 = new Articles();
		articles1.setTitle(title);
		articles1.setDescription(remarkText);
		articles1.setPicurl(imgUrl);
		articles1.setUrl(url);
		list.add(articles1);
		CustomServiceApi.sendNews(openid, list);
	}
	public static void main(String[] args) {
//		ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
//		CustomServiceApi.sendText("o-jR00R80hWFcIV8_8DqmgEhYUjw", "您开始用药了吗\n<a href=\"www.baidu.com\">点击设置用药时间</a>");
//		sendTemplateMsg();
//		List<Record> cc = Db.find("SELECT users.name from account inner join users on account.uid = users.uid where account.openid = 'o-jR00R80hWFcIV8_8DqmgEhYUjw';");
//		System.out.println(cc.size());
//		Db.queryLong(sql)
//		sendCustomerServiceMessage("", "", "", "","");
//		 Calendar now = Calendar.getInstance();  
////		 now.set(Calendar.HOUR_OF_DAY, 19);
//		 now.setTimeInMillis(1483228800000l);
//	        System.out.println("年: " + now.get(Calendar.YEAR));  
//	        System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");  
//	        System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));  
//	        System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));  
//	        System.out.println("分: " + now.get(Calendar.MINUTE));  
//	        System.out.println("秒: " + now.get(Calendar.SECOND));  
//	        System.out.println("当前时间毫秒数：" + now.getTimeInMillis());  
//	        System.out.println(now.getTime());  
//        getUserInfo("o-jR00R80hWFcIV8_8DqmgEhYUjw");
		}
}
